import re
from collections import Counter

import jieba.analyse
from django.forms import model_to_dict
import pandas as pd
from user.models import Position
from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
from django.db.models import *


def get_data(keyword):
    """
    连接数据库通过关键词查询出数据，由视图统一调用
    :param keyword:
    :return: 返回一个职位列表，列表的元素为字典，分别对应一个职位
    """
    data = Position.objects.filter(keyword=keyword)
    return [model_to_dict(i) for i in data]


# 在这下面写每个图的数据分析代码，一个图一个函数，参数统一为上面那个函数的返回值列表
def education_analysis(data):
    """
    学历情况的数据分析
    :param data:
    :return:
    """
    # 将数据集转换为dataframe
    df = pd.DataFrame(data=data)
    # 计算学历的分布情况
    temp = df['education'].value_counts().to_dict()
    return [{'name': k, 'value': v} for k, v in temp.items()]


def salary_analysis(data):
    df = pd.DataFrame(data=data)
    temp = df['salary'].value_counts().to_dict()
    categories = list()
    data = list()
    for k, v in temp.items():
        categories.append(k)
        data.append(v)
    return {'categories': categories, 'data': data}


def location_analysis(data):
    df = pd.DataFrame(data=data)
    dict_data = df['location'].value_counts().to_dict()
    categories = list()
    data = list()
    for k, v in dict_data.items():
        categories.append(k)
        data.append(v)
    return {'categories': categories, 'data': data}


def experience_analysis(data):
    df = pd.DataFrame(data=data)
    dict_data = df['experience'].value_counts().to_dict()
    categories = list()
    data = list()
    for k, v in dict_data.items():
        categories.append(k)
        data.append(v)
    return {'categories': categories, 'data': data}


def profession_analysis(data):
    df = pd.DataFrame(data=data)
    dict_data = df['profession'].value_counts().to_dict()
    return [{'name': k, 'value': v} for k, v in dict_data.items()]


def company_analysis(data):
    df = pd.DataFrame(data=data)
    company_data = df['company'].value_counts().to_dict()
    return [{'name': k, 'value': v} for k, v in company_data.items()]


# 工作要求
def requirement_analysis(data):
    df = pd.DataFrame(data=data)
    df['requirements'].fillna('', inplace=True)
    # 分词
    temp = list()
    for i in df['requirements']:
        temp.extend(re.split(r';|；|，|,|\.|、+', i))
    count = Counter(temp)
    result = sorted(count.items(), key=lambda x: x[1], reverse=True)
    return [{'name': result[item][0], 'value': result[item][1]} for item, j in enumerate(result)]


# 公司福利
def benifits_analysis(data):
    df = pd.DataFrame(data=data)
    df['benifits'].fillna('', inplace=True)

    # 分词
    temp = list()
    for i in df['benifits']:
        temp.extend(re.split(r';|；|，|,|\.|、+', i))

    count = Counter(temp)
    result = sorted(count.items(), key=lambda x: x[1], reverse=True)
    return [{'name': result[item][0], 'value': result[item][1]} for item, j in enumerate(result)]
